<?php

namespace App\Console\Commands\Cruise;

use App\Models\Cruise\CruiseCheckAgainstShopMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Service\Cruise\Check\CruiseCheckAgainstShopMappingsService;
use Illuminate\Console\Command;

class AddCruiseCheckAgainstShopMappings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:add_cruise_check_against_shop_mappings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化违约函门店映射表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //获得当前门店ID，门店编号新建门店违约函版本
        $time      = time();
        $batchData = [];
        OpenShopMainProcessModel::query()
            ->with('signOrderRel')
            ->chunk(500, function ($item) use (&$batchData) {
                foreach ($item as $v) {
                    if ($v->shopId > 0 && $v->signOrderRel) {
                        if ($v->signOrderRel->shopCode > 0) {
                            // 新增门店违约函版本
                            $version               = CruiseCheckAgainstShopMappingsService::getAgainstVersionByShopCode($v->signOrderRel->shopCode);
                            $batchData[$v->shopId] = $version;//shopId防重
                        }
                    }
                }
            });

        if ($batchData) {

            //删除所有数据
            CruiseCheckAgainstShopMappingModel::query()->truncate();

            foreach (array_chunk($batchData, 500, true) as $chunk) {//批量新增
                $insertData = [];
                foreach ($chunk as $k => $v) {
                    $insertData[] = [
                        'shopId'    => $k,
                        'version'   => $v,
                        'createdAt' => $time,
                    ];
                }
                if ($insertData) {
                    CruiseCheckAgainstShopMappingModel::query()->insert($insertData);
                }
            }
        }
    }
}
